<template>
  <div style="padding: 10px">
    <h3>{{ module.type }} 配置</h3>

    <el-form label-position="top" v-if="module">
      <!-- SubjectSelector -->
      <div v-if="module.type === 'SubjectSelector'">
        <el-form label-width="80px">
          <!-- SubjectSelector -->
          <el-form-item label="学科列表">
            <div
              v-for="(item, idx) in localModule.props.subjects"
              :key="idx"
              style="display: flex; align-items: center; margin-bottom: 4px"
            >
              <el-input
                v-model="localModule.props.subjects[idx]"
                size="small"
              />
              <el-button
                icon="el-icon-delete"
                @click="removeSubject(idx)"
                type="text"
              ></el-button>
            </div>
            <div style="margin-top: 8px">
              <el-input
                v-model="newSubject"
                size="small"
                placeholder="新增标题"
                style="width: 70%"
              />
              <el-button type="primary" size="small" @click="addSubject"
                >添加</el-button
              >
            </div>
          </el-form-item>

          <el-form-item label="背景色">
            <el-color-picker
              v-model="localModule.props.bgColor"
              @change="changeBgColor"
            />
          </el-form-item>

          <el-form-item label="文字颜色">
            <el-color-picker v-model="localModule.props.textColor" />
          </el-form-item>

          <el-form-item label="字体大小">
            <el-input
              v-model="localModule.props.fontSize"
              size="small"
              placeholder="如 16px"
            />
          </el-form-item>

          <el-form-item label="内边距">
            <el-input
              v-model="localModule.props.padding"
              size="small"
              placeholder="如 10px"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- Search -->
      <div v-else-if="module.type === 'Search'">
        <el-form-item label="占位符">
          <el-input v-model="localModule.props.placeholder" />
        </el-form-item>
      </div>

      <!-- Banner -->
      <div v-else-if="module.type === 'Banner'">
        <el-form-item label="轮播图列表">
          <div
            v-for="(banner, idx) in localModule.props.banners"
            :key="idx"
            style="
              margin-bottom: 10px;
              display: flex;
              gap: 10px;
              flex-wrap: wrap;
            "
          >
            <el-input
              v-model="banner.title"
              placeholder="标题"
              size="small"
              style="width: 140px"
            />
            <el-input
              v-model="banner.image"
              placeholder="图片链接"
              size="small"
              style="width: 200px"
            />
            <el-input
              v-model="banner.url"
              placeholder="跳转链接"
              size="small"
              style="width: 180px"
            />
            <el-select
              v-model="banner.status"
              placeholder="状态"
              size="small"
              style="width: 100px"
            >
              <el-option label="上架" value="up" />
              <el-option label="下架" value="down" />
            </el-select>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeBanner(idx)"
            />
          </div>

          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="addBanner"
            >添加轮播图</el-button
          >

          <el-button
            type="success"
            size="mini"
            icon="el-icon-search"
            style="margin-left: 8px"
            @click="selectExistingImage"
            >选择现有</el-button
          >
        </el-form-item>
        <el-form-item label="自动播放">
          <el-switch v-model="localModule.props.autoplay" />
        </el-form-item>
      </div>

      <!-- Notice -->
      <div v-else-if="module.type === 'Notice'">
        <el-form-item label="公告内容">
          <el-input type="textarea" v-model="localModule.props.text" rows="3" />
        </el-form-item>
      </div>

      <!-- FunctionEntry -->
      <div v-else-if="module.type === 'FunctionEntry'">
        <el-form-item label="功能入口列表">
          <div
            v-for="(entry, idx) in localModule.props.entries"
            :key="idx"
            style="margin-bottom: 10px"
          >
            <el-input
              v-model="entry.title"
              placeholder="标题"
              size="small"
              style="width: 120px; margin-right: 5px"
            />
            <el-input
              v-model="entry.icon"
              placeholder="图标类名"
              size="small"
              style="width: 120px; margin-right: 5px"
            />rich-text-editor
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeEntry(idx)"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addEntry"
            >添加入口</el-button
          >
        </el-form-item>
      </div>

      <!-- QuickEntry -->
      <div v-else-if="module.type === 'QuickEntry'">
        <el-form-item label="快捷入口列表">
          <div
            v-for="(entry, idx) in localModule.props.entries"
            :key="idx"
            style="margin-bottom: 10px"
          >
            <el-input
              v-model="entry.title"
              placeholder="名称"
              size="small"
              style="width: 120px; margin-right: 5px"
            />
            <el-input
              v-model="entry.link"
              placeholder="跳转链接"
              size="small"
              style="width: 180px; margin-right: 5px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeQuickEntry(idx)"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addQuickEntry"
            >添加快捷入口</el-button
          >
        </el-form-item>
      </div>

      <!-- BrandRecommend -->
      <div v-else-if="module.type === 'BrandRecommend'">
        <el-form-item label="品牌列表">
          <div
            v-for="(brand, idx) in localModule.props.brands"
            :key="idx"
            style="margin-bottom: 10px"
          >
            <el-input
              v-model="brand.name"
              placeholder="品牌名称"
              size="small"
              style="width: 200px; margin-right: 5px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeBrand(idx)"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addBrand"
            >添加品牌</el-button
          >
        </el-form-item>
      </div>

      <!-- RichContent -->
      <div v-else-if="module.type === 'RichContent'">
        <el-form-item label="内容编辑">
          <rich-text-editor
            :content="localModule.props.content"
            @update-content="updateRichContent"
          />
        </el-form-item>
      </div>

      <!-- ImageLink -->
      <div v-else-if="module.type === 'ImageLink'">
        <el-form-item label="上传图片">
          <el-upload
            class="upload-demo"
            action=""
            :http-request="handleImageUpload"
            :show-file-list="false"
          >
            <el-button type="primary">点击上传</el-button>
            <img
              v-if="localModule.props.image"
              :src="localModule.props.image"
              alt="预览图"
              style="margin-top: 10px; max-width: 100px; display: block"
            />
          </el-upload>
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input v-model="localModule.props.link" />
        </el-form-item>
      </div>

      <!-- Video -->
      <div v-else-if="module.type === 'Video'">
        <el-form-item label="视频排版">
          <el-select
            v-model="localModule.props.videoTypesetting"
            placeholder="请选择排版"
            @change="videoTypesetting"
          >
            <el-option
              v-for="item in coursewareOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="视频列表">
          <div
            v-for="(video, idx) in localModule.props.videos"
            :key="idx"
            style="
              margin-bottom: 10px;
              display: flex;
              flex-wrap: wrap;
              gap: 5px;
            "
          >
            <el-input
              v-model="video.title"
              placeholder="视频标题"
              size="small"
              style="width: 140px"
            />
            <el-input
              v-model="video.url"
              placeholder="跳转链接"
              size="small"
              style="width: 180px"
            />
            <el-input
              v-model="video.cover"
              placeholder="封面图片链接"
              size="small"
              style="width: 200px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeVideo(idx)"
            />
          </div>

          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addVideo"
            >添加视频</el-button
          >

          <el-button
            size="mini"
            type="success"
            icon="el-icon-search"
            style="margin-left: 8px"
            @click="selectExistingVideo"
            >选择现有视频</el-button
          >
        </el-form-item>

        <el-form-item label="更多链接">
          <el-input
            v-model="localModule.props.moreUrl"
            placeholder="如 /more-videos"
          />
        </el-form-item>
      </div>

      <!-- Courseware -->
      <div v-else-if="module.type === 'Courseware'">
        <el-form-item label="课件列表">
          <el-select
            v-model="localModule.props.coursewareTypesetting"
            placeholder="请选择排版"
            @change="coursewareTypeSetting"
          >
            <el-option
              v-for="item in coursewareOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div
            v-for="(course, idx) in localModule.props.coursewares"
            :key="idx"
            style="
              margin-bottom: 10px;
              display: flex;
              flex-wrap: wrap;
              gap: 5px;
            "
          >
            <el-input
              v-model="course.title"
              placeholder="课件标题"
              size="small"
              style="width: 140px"
            />
            <el-input
              v-model="course.url"
              placeholder="链接"
              size="small"
              style="width: 180px"
            />
            <el-input
              v-model="course.image"
              placeholder="图片链接"
              size="small"
              style="width: 200px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeCourseware(idx)"
            />
          </div>

          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addCourseware"
            >添加课件</el-button
          >

          <el-button
            size="mini"
            type="success"
            icon="el-icon-search"
            style="margin-left: 8px"
            @click="selectExistingProduct"
            >选择现有课件</el-button
          >
        </el-form-item>

        <el-form-item label="更多链接">
          <el-input
            v-model="localModule.props.moreUrl"
            placeholder="如 /more-coursewares"
          />
        </el-form-item>
      </div>

      <!-- Product -->
      <div v-else-if="module.type === 'Product'">
        <el-form-item label="商品列表">
          <el-select
            v-model="localModule.props.productTypesetting"
            placeholder="请选择排版"
            @change="productTypesetting"
          >
            <el-option
              v-for="item in coursewareOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div
            v-for="(product, idx) in localModule.props.products"
            :key="idx"
            style="
              margin-bottom: 10px;
              display: flex;
              flex-wrap: wrap;
              gap: 5px;
            "
          >
            <el-input
              v-model="product.name"
              placeholder="商品名称"
              size="small"
              style="width: 150px"
            />
            <el-input
              v-model="product.price"
              placeholder="价格"
              size="small"
              type="number"
              style="width: 100px"
            />
            <el-input
              v-model="product.image"
              placeholder="图片链接"
              size="small"
              style="width: 200px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeProduct(idx)"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addProduct"
            >添加商品</el-button
          >

          <el-button
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="selectExistingProduct"
            style="margin-left: 10px"
            >选择现有商品</el-button
          >
        </el-form-item>

        <el-form-item label="更多链接">
          <el-input
            v-model="localModule.props.moreUrl"
            placeholder="如 /more-products"
          />
        </el-form-item>
      </div>

      <!-- Column -->
      <div v-else-if="module.type === 'Column'">
        <el-form-item label="专栏标题">
          <el-input v-model="localModule.props.title" />
        </el-form-item>
        <el-form-item label="专栏内容">
          <el-input
            type="textarea"
            v-model="localModule.props.content"
            rows="4"
          />
        </el-form-item>
      </div>

      <!-- ExternalProduct -->
      <div v-else-if="module.type === 'ExternalProduct'">
        <el-form-item label="外链商品名称">
          <el-input v-model="localModule.props.name" />
        </el-form-item>
        <el-form-item label="外链地址">
          <el-input v-model="localModule.props.url" />
        </el-form-item>
      </div>

      <!-- Vote -->
      <div v-else-if="module.type === 'Vote'">
        <el-form-item label="投票问题">
          <el-input v-model="localModule.props.question" />
        </el-form-item>
        <el-form-item label="选项列表">
          <div
            v-for="(opt, idx) in localModule.props.options"
            :key="idx"
            style="margin-bottom: 5px"
          >
            <el-input
              v-model="localModule.props.options[idx]"
              size="small"
              placeholder="选项"
              style="width: 200px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeOption(idx)"
              style="margin-left: 5px"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addOption"
            >添加选项</el-button
          >
        </el-form-item>
      </div>

      <!-- ContentList -->
      <div v-else-if="module.type === 'ContentList'">
        <el-form-item label="内容列表">
          <div
            v-for="(item, idx) in localModule.props.items"
            :key="idx"
            style="margin-bottom: 5px"
          >
            <el-input
              v-model="localModule.props.items[idx]"
              size="small"
              placeholder="内容项"
              style="width: 250px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeItem(idx)"
              style="margin-left: 5px"
            />
          </div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addItem"
            >添加内容</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-button
      type="primary"
      size="small"
      @click="saveChanges"
      style="margin-top: 10px"
      >保存配置</el-button
    >
    <el-dialog title="选择商品" :visible.sync="showProductDialog" width="600px">
      <el-table :data="productList" style="width: 100%">
        <el-table-column prop="goodId" label="ID" width="80" />
        <el-table-column prop="goodName" label="商品名称" />
        <el-table-column prop="goodOriginalPrice" label="价格" />
        <el-table-column label="操作" width="120">
          <template slot-scope="{ row }">
            <el-button size="mini" @click="selectProductItem(row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showProductDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RichTextEditor from "./modules/RichTextEditor.vue";
import { selectProduct } from "@/api/modules";
export default {
  props: {
    module: {
      type: Object,
      required: true,
    },
  },
  components: {
    RichTextEditor,
  },
  data() {
    return {
      localModule: JSON.parse(JSON.stringify(this.module)), // 深拷贝用于编辑
      newSubject: "",
      productList: [],
      showProductDialog: false,
      coursewareOptions: [
        {
          value: "24",
          label: "竖排",
        },
        {
          value: "12",
          label: "横排",
        },
      ],
    };
  },
  watch: {
    module: {
      immediate: true,
      handler(newVal) {
        this.localModule = JSON.parse(JSON.stringify(newVal));
        this.newSubject = "";
      },
    },
  },
  methods: {
    // SubjectSelector
    addSubject() {
      const val = this.newSubject.trim();
      if (!val) return;
      // 初始化 props 和 subjects 数组
      if (!this.localModule.props) this.localModule.props = {};
      if (!Array.isArray(this.localModule.props.subjects)) {
        this.localModule.props.subjects = [];
      }
      if (!this.localModule.props.subjects.includes(val)) {
        this.localModule.props.subjects.push(val);
        this.newSubject = "";
        this.emitUpdate();
      }
    },
    changeBgColor() {
      this.emitUpdate();
    },
    removeSubject(index) {
      if (
        this.localModule.props &&
        Array.isArray(this.localModule.props.subjects)
      ) {
        this.localModule.props.subjects.splice(index, 1);
        this.emitUpdate();
      }
    },
    emitUpdate() {
      const updatedModule = {
        ...this.module,
        props: { ...this.localModule.props },
      };
      this.$emit("update-module", updatedModule);

      if (this.module.type === "SubjectSelector") {
        const bgColor = this.localModule.props.bgColor; // 注意这里直接取根级 bgColor
        this.$emit("sync-search-bg", bgColor);
        this.$emit("sync-banner-bg", bgColor);
      }
    },

    // Banner
    addBanner() {
      if (!this.localModule.props.banners) {
        this.$set(this.localModule.props, "banners", []);
      }
      this.localModule.props.banners.push({
        title: "",
        image: "",
        url: "",
        status: "up", // 默认上架
      });
    },
    removeImage(index) {
      this.localModule.props.images.splice(index, 1);
    },
    selectExistingImage() {},

    // FunctionEntry
    addEntry() {
      if (!this.localModule.props.entries) {
        this.$set(this.localModule.props, "entries", []);
      }
      this.localModule.props.entries.push({ icon: "", title: "" });
    },
    removeEntry(index) {
      this.localModule.props.entries.splice(index, 1);
    },

    // QuickEntry
    addQuickEntry() {
      this.localModule.props.entries.push({
        title: "",
        link: "",
      });
    },
    removeQuickEntry(index) {
      this.localModule.props.entries.splice(index, 1);
    },

    // BrandRecommend
    addBrand() {
      if (!this.localModule.props.brands) {
        this.$set(this.localModule.props, "brands", []);
      }
      this.localModule.props.brands.push({ name: "" });
    },
    removeBrand(index) {
      this.localModule.props.brands.splice(index, 1);
    },

    // Vote
    addOption() {
      if (!this.localModule.props.options) {
        this.$set(this.localModule.props, "options", []);
      }
      this.localModule.props.options.push("");
    },
    removeOption(index) {
      this.localModule.props.options.splice(index, 1);
    },

    // ContentList
    addItem() {
      if (!this.localModule.props.items) {
        this.$set(this.localModule.props, "items", []);
      }
      this.localModule.props.items.push("");
    },
    removeItem(index) {
      this.localModule.props.items.splice(index, 1);
    },

    // 富文本内容更新
    updateRichContent(newContent) {
      this.localModule.props.content = newContent;
      this.$emit("update-module", this.localModule);
    },

    // 保存
    saveChanges() {
      this.$emit("update-module", this.localModule);
      this.$message.success("模块配置已保存");
    },
    handleImageUpload(option) {
      const file = option.file;
      const reader = new FileReader();
      reader.onload = (e) => {
        this.localModule.props.image = e.target.result; // base64
      };
      reader.readAsDataURL(file);
    },

    //courseware
    coursewareTypeSetting(value) {
      this.localModule.props.coursewareTypesetting = value;
      console.log(this.localModule.props.coursewareTypesetting);
    },
    addCourseware() {
      if (!this.localModule.props.coursewares) {
        this.$set(this.localModule.props, "coursewares", []);
      }
      this.localModule.props.coursewares.push({
        title: "",
        url: "",
        image: "",
      });
    },
    removeCourseware(index) {
      this.localModule.props.coursewares.splice(index, 1);
    },
    selectExistingCourseware() {
      // TODO: 请求后端接口，选择现有课件
      console.log("准备接入后端接口，选择已有课件");
    },
    //video
    addVideo() {
      if (!this.localModule.props.videos) {
        this.$set(this.localModule.props, "videos", []);
      }
      this.localModule.props.videos.push({
        title: "",
        url: "",
        cover: "",
      });
    },
    removeVideo(idx) {
      this.localModule.props.videos.splice(idx, 1);
    },
    selectExistingVideo() {
      // 打开弹窗/接口选择已有视频
    },
    videoTypesetting(value) {
      this.localModule.props.videoTypesetting = value;
    },

    //product
    productTypesetting(value) {
      this.localModule.props.productTypesetting = value;
      console.log(this.localModule.props.coursewareTypesetting);
    },
    addProduct() {
      window.open("/addProduct", "_blank");
      // if (!this.localModule.props.products) {
      //   this.$set(this.localModule.props, "products", []);
      // }
      // this.localModule.props.products.push({
      //   name: "",
      //   price: "",
      //   image: "",
      // });
    },
    removeProduct(index) {
      this.localModule.props.products.splice(index, 1);
    },
    async selectExistingProduct() {
      try {
        const res = await selectProduct();
        this.productList = res.rows || [];
        this.showProductDialog = true;
        console.log(this.productList);
      } catch (error) {
        this.$message.error("获取商品失败");
      }
    },
    selectProductItem(product) {
      this.$message.success(`你选择了商品：${product.goodName}`);
      const good = {
        name: product.goodName,
        image: product.goodPicture,
        price: product.goodMemberPrice,
        // 如果前端还有用到的字段可以继续映射
      };
      this.showProductDialog = false;
      if (!this.localModule.props) {
        this.$set(this.localModule, "props", {});
      }
      if (!Array.isArray(this.localModule.props.products)) {
        this.$set(this.localModule.props, "products", []);
      }
      this.localModule.props.products.push(good);
    },
  },
};
</script>
